import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { request } from "../../utils";

export interface CarItem {
  color: string;
  size: string;
  count: number;
  title: string;
  id: string;
  desc: string;
  url: string;
  price: number
}

interface CarState {
  loading: boolean;
  error: null | string;
  car: CarItem[];
}

const initialState: CarState = {
  loading: true,
  error: null,
  car: [],
};

const carSlice = createSlice({
  name: "classify",
  initialState,
  reducers: {
    addCar(state, action: PayloadAction<CarItem>) {
      const item = state.car.find((v) => v.id === action.payload.id);
      if (item) {
        item.count += action.payload.count;
      } else {
        state.car.unshift(action.payload);
      }
    },
    addCarItemCount(state, action: PayloadAction<CarItem>) {
      const item = state.car.find((v) => v.id === action.payload.id);
      if (item) {
        item.count++;
      }
    },
    subCarItemCount(state, action: PayloadAction<CarItem>) {
      const item = state.car.find((v) => v.id === action.payload.id);
      if (item) {
        item.count--;
      }
    },
  },
});

export const { addCar, addCarItemCount, subCarItemCount } = carSlice.actions;
export default carSlice;
